import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'

Vue.use(Router);

function route (path, file, name, children) {
  return {
    exact: true,
    path,
    name,
    children,
    component: () => import('../pages' + file)   //route()方法默认路由到../pages路径下
  }
}

// 页面刷新时，重新赋值token
if (sessionStorage.getItem('token')) {
  store.commit('set_token', sessionStorage.getItem('token'))
}

const router = new Router({
  mode: "history",
  routes: [
    route("/login",'/Login',"Login"),// /login路径，路由到登录组件  http://localhost:9000/login
    {
      path:"/", // 根路径，路由到 Layout组件
      component: () => import('../pages/Layout'),
      redirect:"/index/dashboard",
      children:[ // 其它所有组件都是 Layout的子组件
        route("/index/dashboard","/Dashboard","Dashboard"),
        route("/index/processApply","/ProcessApply","ProcessApply"),
        route("/template/code",'/item/CodeGenerator',"CodeGenerator"),
        route("/template/word",'/item/Brand',"Brand"),
        route("/template/list",'/item/Goods',"Goods"),
        route("/template/specification",'/item/specification/Specification',"Specification"),
        route("/mock/interface", "/mock/Interface", "Interface"),
        route("/mock/data", "/mock/DataGenerator", "DataGenerator"),
        route("/mock/word", "/mock/Interface", "Interface"),
        route("/system/resource",'/system/Resource',"Resource"),
        route("/system/role",'/system/Role',"Role"),
        route("/system/people",'/system/People',"People"),
        route("/schedule/list",'/schedule/List',"List"),
        route("/schedule/config",'/schedule/Config',"Config"),
        route("/schedule/log",'/schedule/Log',"Log"),
        route("/process/define",'/process/Design',"design"),
        route("/process/model",'/process/Model',"Model"),
        route("/process/auth",'/process/Auth',"Auth"),
        route("/process/log",'/process/Log',"Log"),
      ]
    }
  ]
});

router.beforeEach((to, from, next) => {
  //这里的requireAuth为路由中定义的 meta:{requireAuth:true}，意思为：该路由添加该字段，表示进入该路由需要登陆的
  if (to.matched.some(r => r.meta.requireAuth)) {
    if (store.state.token) {
      next();
    }
    else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    }
  }
  else {
    next();
  }
});
export default router;
